// pages/mch/car/update.js
const App = getApp()
import Util from '../../../utils/util'

Page({
  data: {
    init: false,
    loading: false,

    top: App.Global.StatusBar + App.Global.CustomBar,

    steps: ["上传行车证", "车辆信息", "价格/分润", "增值服务"],
    step: 1,


    mer: {},
    conf: {},

    car: {},

    activeNames: ['1'],

    colors: [],

    vlca: '',
    photo: '',
    sid: '',
    name: '',
    cno: '',
    vin: '',
    eno: '',
    attr_fuel: '',
    attr_color: '',
    attr_year: new Date().getFullYear(),
    attr_liter: '',
    attr_seat: 0,
    attr_door: 0,
    attr_gearauto: true,
    price_pdp: 0,
    price_pmp: 0,
    price_mdp: 0,
    price_deposit: 0,
    price_disp: 0,
    settle_type: 1,
    settle_rent_base_amt: 0,
    settle_rent_base_uid: '',
    settle_rent_base_name: '',
    settle_rent_spliter: [],
    settle_rate_spliter: [],
    service_onsite_flag: false,
    service_remote_flag: false,
    service_bins_flag: false,
    service_dins_flag: false,
    service_tins_flag: false,
    service_free_flag: false,
    service_night_flag: false,
    service_waive_flag: false,

  },
  onLoad(options) {
    App.doPost({
      uri: '/app/merchant/conf/detail',
      body: {},
      fnSucc: resp => {
        this.setData({
          mer: resp.data,
          conf: resp.data.city,
        })
        this.execLoad(options.cid)
      },

    })
  },

  execLoad(cid) {
    App.doPost({
      uri: '/app/merchant/car/detail',
      body: {
        id: cid
      },
      fnSucc: resp => {
        this.setData({
          init: true,
          car: resp.data,

          vlca: resp.data.vlc.pica,
          photo: resp.data.photo,
          sid: resp.data.sid,
          name: resp.data.name,
          cno: resp.data.cno,
          vin: resp.data.vin,
          eno: resp.data.eno,
          attr_color: resp.data.attr.color,
          attr_year: resp.data.attr.year,
          attr_liter: resp.data.attr.liter,
          attr_seat: resp.data.attr.seat,
          attr_door: resp.data.attr.door,
          attr_gearauto: resp.data.attr.gearauto,
          attr_fuel: resp.data.attr.fuel,
          price_pdp: resp.data.price.pdp / 100,
          price_pmp: resp.data.price.pmp / 100,
          price_mdp: resp.data.price.mdp / 100,
          price_deposit: resp.data.price.deposit / 100,
          price_disp: resp.data.price.disp / 100,
          settle_type: 1, //resp.data.settle.type,
          settle_rent_base_amt: resp.data.settle.rent.base.amt / 100,
          settle_rent_base_uid: resp.data.settle.rent.base.uid,
          settle_rent_base_name: resp.data.settle.rent.base.name,
          settle_rent_spliter: resp.data.settle.rent.spliter.map(s => {
            return {
              amt: s.amt / 100,
              rate: s.rate / 10,
              uid: s.uid,
              name: s.name,
              type: s.type,
              sort: s.sort
            }
          }),
          settle_rate_spliter: resp.data.settle.rate.spliter.map(s => {
            return {
              rate: s.rate / 10,
              uid: s.uid,
              name: s.name,
              sort: s.sort
            }
          }),
          service_onsite_flag: resp.data.service.onsite.flag,
          service_remote_flag: resp.data.service.remote.flag,
          service_bins_flag: resp.data.service.bins.flag,
          service_dins_flag: resp.data.service.dins.flag,
          service_tins_flag: resp.data.service.tins.flag,
          service_free_flag: resp.data.service.free.flag,
          service_night_flag: resp.data.service.night.flag,
          service_waive_flag: resp.data.service.waive.flag,
        })
      }
    })
  },
  doPrve() {
    this.setData({
      step: this.data.step - 1
    })
  },

  doNextInfo() {
    if (this.data.vin == this.data.car.vin) {
      this.setData({
        step: 2
      })
      return
    }
    if (!this.data.cno || !this.data.vin || !this.data.eno) {
      return
    }
    App.doPost({
      uri: '/comm/tool/vin/data',
      body: {
        vin: this.data.vin,
        eno: this.data.eno
      },
      fnSucc: resp => {
        this.setData({
          step: 2,
          sid: resp.data.serie.id,
          attr_year: resp.data.year,
          attr_liter: resp.data.liter,
          attr_gearauto: resp.data.gearauto,
          attr_door: resp.data.door,
          attr_seat: resp.data.seat,
          attr_fuel: resp.data.fuel,
          name: resp.data.name,
        })
      },
      fnFail: (resp) => {
        if (resp.stat.err == 70) {
          Util.Notify.warn(`VIN码不正确，请填写正确或修改识别VIN码`)
        } else if (resp.stat.err == 71 || resp.stat.err == 72 || resp.stat.err == 73) {
          Util.Notify.warn(`未能成功识别车型，请仔细填写车辆资料`)
          this.setData({
            step: 2
          })
        } else {
          Util.Notify.warn(`[${resp.stat.err}] ${resp.stat.msg}`)
        }
      }
    })
  },

  doNextPrice() {
    this.setData({
      step: 3
    })
  },
  doNextService() {
    if (parseFloat(this.data.price_mdp) <= parseFloat(this.data.price_pdp)) {
      Util.Notify.warn(`同行价格不得高于门店价格`)
      return
    }
    if (parseFloat(this.data.price_pmp) <= parseFloat(this.data.price_pdp)) {
      Util.Notify.warn(`同行月租价格不得低于日租价格`)
      return
    }
    if (parseInt(this.data.price_deposit * 100) <= 2000 * 100) {
      Util.Notify.warn(`车辆押金不得低于违章押金2000元`)
      return
    }
    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_amt <= 0 || this.data.settle_rent_base_uid == '') {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    if (this.data.settle_type == 3) {
      if (this.data.settle_rate_spliter.length <= 0) {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }

    let k = 1
    let rate_spliter = this.data.settle_rate_spliter.map(spliter => {
      return {
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        sort: k++,
      }
    })
    if (this.data.settle_type == 3) {
      let max = rate_spliter.reduce((p, c) => p + c.rate, 0)
      if (max != 1000) {
        Util.Notify.warn(`请设置正确的租金分配比例`)
        return
      }
    }
    this.setData({
      step: 4
    })
  },



  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  doSelectUser() {
    let amt = true
    let rate = true
    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_uid == '') {
        rate = false
      }
    } else {
      amt = false
    }
    wx.navigateTo({
      url: `/pages/mch/car/user?type=${this.data.settle_type}&amt=${amt}&rate=${rate}`,
      events: {
        enter: (seld) => {
          if (this.data.settle_type == 2) {
            if (this.data.settle_rent_base_uid == '') {
              this.setData({
                settle_rent_base_amt: parseFloat(seld.amt),
                settle_rent_base_uid: seld.uid,
                settle_rent_base_name: seld.name,
              })
            } else {
              let spliter = this.data.settle_rent_spliter
              spliter[spliter.length] = {
                uid: seld.uid,
                name: seld.name,
                type: seld.type,
                amt: parseFloat(seld.amt),
                rate: parseFloat(seld.rate),
              }
              let idx = 1
              spliter.forEach(s => {
                s.sort = s.uid == 'share' ? 99999 : idx++
              })
              spliter.sort((m, n) => {
                return m.sort - n.sort
              })

              this.setData({
                settle_rent_spliter: spliter
              })
            }
          } else {
            let spliter = this.data.settle_rate_spliter
            spliter[spliter.length] = {
              uid: seld.uid,
              name: seld.name,
              rate: parseFloat(seld.rate),
            }
            this.setData({
              settle_rate_spliter: spliter
            })
          }

        }
      }
    })
  },
  doDelRentSpliter() {
    let spliter = this.data.settle_rent_spliter
    if (spliter.length > 0) {
      spliter.length = spliter.length - 1
      this.setData({
        settle_rent_spliter: spliter
      })
    } else {
      this.setData({
        settle_rent_base_amt: 0,
        settle_rent_base_uid: '',
        settle_rent_base_name: '',
      })
    }
  },
  doDelRateSpliter() {
    let spliter = this.data.settle_rate_spliter
    if (spliter.length > 0) {
      spliter.length = spliter.length - 1
      this.setData({
        settle_rate_spliter: spliter
      })
    }
  },
  doCertChange(e) {
    let odata = {}
    odata.vlca = e.detail.url

    if (e.detail.ocr.cno) {
      odata["cno"] = e.detail.ocr.cno
      odata["vin"] = e.detail.ocr.vin
      odata["eno"] = e.detail.ocr.eno
      odata["name"] = (this.data.car.vin == e.detail.ocr.vin ? this.data.car.name : '') || e.detail.ocr.model
    } else {
      odata["cno"] = ''
      odata["vin"] = ''
      odata["eno"] = ''
      odata["name"] = ''
    }
    this.setData({
      ...odata
    })
  },
  doPictChange(e) {
    let odata = {}
    odata[e.target.dataset.type] = e.detail.url
    this.setData({
      ...odata
    })
  },
  doSettleChange(e) {
    this.setData({
      settle_type: parseInt(e.currentTarget.dataset.type)
    })
  },
  doCheckInput(e) {
    let value = parseFloat(e.detail.value || '0')
    let min = parseFloat(e.target.dataset.min || '0')
    let max = parseFloat(e.target.dataset.max || '99999')
    if (value < min) {
      return min + ''
    }
    if (value > max) {
      return max + ''
    }
    return parseFloat(value.toFixed(2)) + ''
  },
  doSaveInfo() {

    if (!this.data.photo) {
      Util.Notify.warn(`请上传实车照片`)
      return
    }
    if (!this.data.name) {
      Util.Notify.warn(`请填写车型名称`)
      return
    }
    if (!this.data.cno) {
      Util.Notify.warn(`请填写车牌号码`)
      return
    }
    if (!this.data.vin) {
      Util.Notify.warn(`请填写车架编号`)
      return
    }
    if (!this.data.eno) {
      Util.Notify.warn(`请填写发动机号`)
      return
    }
    if (!this.data.attr_year) {
      Util.Notify.warn(`请填写车型年款`)
      return
    }
    if (!this.data.attr_liter) {
      Util.Notify.warn(`请填写车型排量`)
      return
    }
    if (!this.data.attr_color) {
      Util.Notify.warn(`请填写车辆颜色`)
      return
    }
    if (parseInt(this.data.price_mdp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`终端价格不得低于同行价格`)
      return
    }
    if (parseInt(this.data.price_pmp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`同行月租价格不得低于日租价格`)
      return
    }
    if (parseInt(this.data.price_deposit * 100) <= 2000 * 100) {
      Util.Notify.warn(`车辆押金不得低于违章押金2000元`)
      return
    }

    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_amt <= 0 || this.data.settle_rent_base_uid == '') {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    if (this.data.settle_type == 3) {
      if (this.data.settle_rate_spliter.length <= 0) {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    let i = 1
    let rent_spliter = this.data.settle_rent_spliter.map(spliter => {
      return {
        amt: parseInt(spliter.amt * 100),
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        type: spliter.type,
        sort: i++,
      }
    })

    let k = 1
    let rate_spliter = this.data.settle_rate_spliter.map(spliter => {
      return {
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        sort: k++,
      }
    })
    if (this.data.settle_type == 3) {
      let max = rate_spliter.reduce((p, c) => p + c.rate, 0)
      if (max != 1000) {
        Util.Notify.warn(`请设置正确的租金分配比例`)
        return
      }
    }

    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/merchant/car/edit',
      body: {
        id: this.data.car.id,
        vlca: this.data.vlca,
        photo: this.data.photo,
        sid: this.data.sid,
        name: this.data.name,
        cno: this.data.cno,
        vin: this.data.vin,
        eno: this.data.eno,
        service: {
          onsite: {
            flag: this.data.service_onsite_flag && this.data.conf.service.onsite.flag && this.data.mer.service.onsite.flag
          },
          remote: {
            flag: this.data.service_remote_flag && this.data.conf.service.remote.flag && this.data.mer.service.remote.flag
          },
          bins: {
            flag: this.data.service_bins_flag && this.data.conf.service.bins.flag && this.data.mer.service.bins.flag
          },
          dins: {
            flag: this.data.service_dins_flag && this.data.conf.service.dins.flag && this.data.mer.service.dins.flag
          },
          tins: {
            flag: this.data.service_tins_flag && this.data.conf.service.tins.flag && this.data.mer.service.tins.flag
          },
          free: {
            flag: this.data.service_free_flag && this.data.conf.service.free.flag && this.data.mer.service.free.flag
          },
          night: {
            flag: this.data.service_night_flag && this.data.conf.service.night.flag && this.data.mer.service.night.flag
          },
          waive: {
            flag: this.data.service_waive_flag && this.data.conf.service.waive.flag && this.data.mer.service.waive.flag
          }
        },
        attr: {
          color: this.data.attr_color,
          liter: this.data.attr_liter,
          seat: parseInt(this.data.attr_seat + ''),
          door: parseInt(this.data.attr_door + ''),
          gearauto: this.data.attr_gearauto,
          year: parseInt(this.data.attr_year + ''),
          fuel: this.data.attr_fuel || '未知',
        },
        price: {
          pdp: parseInt(this.data.price_pdp * 100),
          pmp: parseInt(this.data.price_pmp * 100),
          mdp: parseInt(this.data.price_mdp * 100),
          deposit: parseInt(this.data.price_deposit * 100),
          disp: parseInt(this.data.price_disp * 100)
        },
        settle: {
          type: this.data.settle_type,
          rent: {
            base: {
              amt: parseInt(this.data.settle_rent_base_amt * 100),
              uid: this.data.settle_rent_base_uid
            },
            spliter: rent_spliter
          },
          rate: {
            spliter: rate_spliter
          }
        }
      },
      fnSucc: () => {
        wx.pub("ReloadCarList", {})
        Util.Toast.succ(`提交成功`)
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000);
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })

  }
})